import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import 'package:situation/app/router/router_name.dart';
import 'package:situation/data/bus/intercom_bus.dart';
import 'package:situation/data/database/sql_provider.dart';
import 'package:situation/data/request/base_request.dart';
import 'package:situation/data/store/auth_store.dart';
import 'package:situation/domain/db/im_msg_content_domain.dart';
import 'package:situation/resources/assets.dart';
import 'package:situation/shared/shared.dart';
import 'package:dio/dio.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart' hide FormData;
import 'package:situation/shared/util/util_intercom.dart';

class IntercomChannel extends GetxController {
  int GW_PTT_EVENT_ERROR = -1;
  int GW_PTT_EVENT_LOGIN = 0;
  int GW_PTT_EVENT_QUERY_GROUP = 1;
  int GW_PTT_EVENT_JOIN_GROUP = 2;
  int GW_PTT_EVENT_QUERY_MEMBER = 3;
  int GW_PTT_EVENT_REQUEST_MIC = 4;
  int GW_PTT_EVENT_TMP_GROUP_ACTIVE = 5;
  int GW_PTT_EVENT_TMP_GROUP_PASSIVE = 6;
  int GW_PTT_EVENT_DUPLEX = 7;
  int GW_PTT_EVENT_LOGOUT = 8;
  int GW_PTT_EVENT_KICKOUT = 9;
  int GW_PTT_EVENT_CURRENT_GROUP = 10;
  int GW_PTT_EVENT_SPEAK = 11;
  int GW_PTT_EVENT_PLAY_DATA = 12;
  int GW_PTT_EVENT_LOSTMIC = 13;
  int GW_PTT_EVENT_GROUP_OPERATE = 15;
  int GW_PTT_EVENT_QUERY_DISPATCH = 16;
  int GW_PTT_EVENT_FRIEND_OPERATE = 17;
  int GW_PTT_EVENT_QUERY_CHAT_GRP = 18;
  int GW_PTT_EVENT_CHAT_GRP_DETAIL = 19;
  int GW_PTT_EVENT_CHAT_SESS_ACTION = 20;
  int GW_PTT_EVENT_CHAT_MSG_DETAIL = 21;
  int GW_PTT_EVENT_CHAT_SEND_MSG = 22;

  int LOCATION_EVENT = 300001;
  int LOCATION_CHANGE_EVENT = 300002;

  String GWSD_CURRENT_GROUP_NAME = "GWSD_CURRENT_GROUP_NAME";
  String GWSD_GROUP = "GWSD_GROUP";

  String EVENT_SEND_TEXT_MSG = "sendTextMsg";
  String EVENT_SEND_PHOTO_OR_VIDEO = "sendPhotoOrVideo";
  String EVENT_VOICE_CALL = "onBtnVoiceCall";
  String EVENT_VIDEO_CALL = "onBtnVideoCall";

  static IntercomChannel get to => Get.find();

  static const String CHANNEL_NAME = "com.sxbdjw.channel.intercom";

  late BasicMessageChannel<dynamic> channel;

  @override
  Future<void> onInit() async {
    super.onInit();
    channel = BasicMessageChannel(CHANNEL_NAME, JSONMessageCodec());
    channel.setMessageHandler(handler);
    print("------------  传输启动OK IntercomChannel onInit  ------------");
  }

  login(username, password) {
    sendMsg({"event": "login", "account": username, "password": password});

    Future.delayed(Duration(seconds: 3), () {
      getGroup();
    });
  }

  getGroup() {
    sendMsg({"event": "queryGroup"});
  }

  /// 监听来自 Android端 的消息通道
  /// Android端调用了函数，这个handler函数就会被触发
  Future<dynamic> handler(dynamic message) async {
    if(AppConstant.printLog){
      print("消息接收 | ${message['event']}"  + " | " + message['msg']);
    }

    IntercomBus.to.sendEvent(IntercomEvent(message['event'], message['msg']));

    if (message['event'] == GW_PTT_EVENT_JOIN_GROUP) {
      // 当前群组
      UtilSp.putString(GWSD_CURRENT_GROUP_NAME, message['msg']);
    }
    if (message['event'] == GW_PTT_EVENT_QUERY_GROUP) {
      // 所有群组
      UtilSp.putString(GWSD_GROUP, message['msg']);
    }

    // if (message['event'] == GW_PTT_EVENT_CHAT_MSG_DETAIL) {
    //   final player = AudioPlayer(); // Create a player
    //   await player.setAsset(Assets.voiceWxvoice);
    //   player.play();
    //   // FlutterTts flutterTts = FlutterTts();
    //   // await flutterTts.setLanguage("zh-CN");
    //   // await flutterTts.setSpeechRate(0.6);
    //   // await flutterTts.speak("你有一条新消息");
    //   // 收到消息了
    //   var msg = json.decode(message['msg']);
    //
    //   var imData = msg['data'];
    //   imData['loginUser'] = AuthStore.to.profile.id;
    //   imData['time'] = msg['time'];
    //   imData['type'] = msg['type'];
    //   imData['remark'] = msg['remark'];
    //   imData['from'] = msg['from'];
    //
    //   // imData 中去掉 remind
    //   imData.remove("remind");
    //   imData.remove("reference");
    //   imData.remove("delete");
    //
    //   SqlProvider.instance.insert(ImMsgContentDomain.tableName, imData);
    //   IntercomEvent event = IntercomEvent(message['event'], imData);
    //   IntercomBus.to.sendEvent(event);
    //
    //   // 判断当前在哪个路由
    //   if (Get.currentRoute != RouterName.communicationChat) {
    //     SmartDialog.showToast("收到新消息");
    //   }
    // }

    if (message['event'] == LOCATION_EVENT) {
      var msg = json.decode(message['msg']);
      var lat = msg['lat'];
      var lon = msg['lon'];
      UtilSp.putString(AppConstant.DEVICE_POSITION, '${lat},${lon}');
      IntercomEvent event = IntercomEvent(LOCATION_EVENT, msg);
      IntercomBus.to.sendEvent(event);

      if(AuthStore.to.isLogin){
        BaseRequest.savePosition({
          "id": AuthStore.to.profile.idcard,
          "dataCode": AuthStore.to.profile.dataCode,
          "position": "",
          "lon": "${lon}",
          "lat": "${lat}",
          "source": "兵馨上报",
        });
      }
    }

    // if (message['event'] == LOCATION_CHANGE_EVENT) {
    //   print("收到新位置：" + message['msg']);
    //   var msg = json.decode(message['msg']);
    //   var lat = msg['lat'];
    //   var lon = msg['lon'];
    //
    //   UtilSp.putString(AppConstant.DEVICE_POSITION, '${lat},${lon}');
    //   IntercomEvent event = IntercomEvent(LOCATION_CHANGE_EVENT, msg);
    //   IntercomBus.to.sendEvent(event);
    //   // 请求位置
    //   // 发送位置
    //   BaseRequest.savePosition({
    //     "id": AuthStore.to.profile.idcard,
    //     "dataCode": "RY",
    //     "position": "",
    //     "lon": "${lon}",
    //     "lat": "${lat}",
    //     "source": "兵馨上报",
    //   });
    // }

    return 0; // 返回给Android端
  }

  /**
   * 消息发送
   */
  sendMsg(message) {
    channel.send(message);
  }

  getLocation() async {
    sendMsg({"event": "getLocation"});
  }

  // 上传文件
  Future<String> uploadFile(filePath) async {
    var data = await UtilIntercom().postForm("", data: filePath);
    var url = data["data"]["file1"]["url"];
    print(url);
    return url;
  }
}
